package stackdemo;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86131
 * Date: 2023-12-06
 * Time: 16:45
 */
public class MyStack {
    public int[] elem;
    public int usedSize;  //默认为0
    public static final int DEFAULT_CAPACITY = 10;
    public MyStack(){  //构造方法
        this.elem = new int[DEFAULT_CAPACITY]; //默认10个元素空间
    }


    //把元素放入栈(压栈)
    public void push(int val){
        //先检查栈空间是否已满
        if(isFull()){
            this.elem = Arrays.copyOf(elem,2*elem.length); //2倍扩容
        }
        elem[usedSize++] = val;  //元素放在usedsize位置并++
    }
    public boolean isFull(){
        return usedSize == elem.length;  //记录元素个数和数组长度一样说明满了
    }

    public int pop(){  //出栈
        if(isEmpty()){
            throw new EmptyStackException("栈为空");
        }
        int val = elem[usedSize-1];
        usedSize--;
        return val;
    }
    public boolean isEmpty(){  //判断栈空间是否为0
        return usedSize == 0;
    }

    public int peek(){  //获取栈顶元素
        if(isEmpty()){
            throw new EmptyStackException("栈为空");
        }
        int val = elem[usedSize-1];
        return val;
    }

}
